package com.mycommune.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.mycommune.persistence.EntityManagerFactoryImpl;

public class ChatSessionFactory {
	private ChatSessionFactory() {
	}

	private static ChatSessionFactory _chatSessionFactory = new ChatSessionFactory();
	private static Map<String, ChatSession> _chatsessionMap = new HashMap<String, ChatSession>();

	public static ChatSession getChatSession(String sessionKey) {
		ChatSession chatSession = _chatsessionMap.get(sessionKey);
		if (null == chatSession) {
			chatSession = _chatSessionFactory.new ChatSession();
			_chatsessionMap.put(sessionKey, chatSession);
		}
		return chatSession;
	}

	public class ChatSession {
		public static final int SELECT = 1;
		public static final int BLANK = 0;
		private String _object;
		private int _option;

		public int getOption() {
			return _option;
		}

		public void setOption(int option) {
			this._option = option;
		}

		public Object getObject() {
			return _object;
		}

		public void setObject(String object) {
			this._object = object;
		}

		public void loadObject(String body) {
			try {
				Class clazz = Class.forName(body);
				setObject(clazz.getName());
			} catch (ClassNotFoundException e) {
				System.out.println("Class not found");
			}
		}

		public Object loadAllEntities() {
			try{
				EntityManager em = EntityManagerFactoryImpl.get()
						.createEntityManager();
	
				Query query = em.createQuery("SELECT e FROM "+getObject()+" e");
				return query.getResultList();
			}
			catch(Throwable e){
				return null;
			}
		}
	}
}
